package com.cf.redis.autoconfigure;

import com.cf.redis.core.annotation.RedisListener;
import com.cf.spel.SpELService;
import com.cf.util.SpringBeanUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.PatternTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.adapter.MessageListenerAdapter;

import java.util.Map;

/**
 * boot-redis-BootRedisAutoConfig
 *
 * @author <a href="2428922347@qq.com">Zhu mingming</a>
 * @info
 * @since 2018/7/13 下午 02:58
 */
@Slf4j
@Configuration
public class BootRedisAutoConfig {

    @Autowired
    private SpELService spELService;

    @Autowired
    private SpringBeanUtil springBeanUtil;

    @Autowired
    private ApplicationContext applicationContext;


    //##################################redis-推送结果通知##########################
    @Bean
    public RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {
        log.info("实例化RedisMessageListenerContainer");
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        Map<String, Object> beansWithAnnotation = springBeanUtil.getBeanWithAnnotation(RedisListener.class);
        if (beansWithAnnotation == null || beansWithAnnotation.size() == 0)
            log.info("未找到包含RedisListener的bean，不执行注册任务");

        beansWithAnnotation.entrySet().forEach(stringObjectEntry -> {
            Object value = stringObjectEntry.getValue();
            RedisListener annotation = value.getClass().getAnnotation(RedisListener.class);
            if (annotation == null) {
                log.info("当前bean未包含RedisListener，忽略，但为什么会会去到这个bean呢");
                return;
            }
            String topic = spELService.getSpELValue(annotation.topic(), String.class);
            log.info("注册监听【{}】", topic);
            MessageListenerAdapter messageListenerAdapter = new MessageListenerAdapter(value, annotation.method());
            messageListenerAdapter.afterPropertiesSet();
            container.addMessageListener(messageListenerAdapter, new PatternTopic(topic));
        });
        return container;
    }
}
